//
//  MonthViewController.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/4.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import RealmSwift

protocol MonthViewControllerDelegate {
    func monthViewControllerToDayViewController(date: NSDate, openUpHeight: CGFloat)
}

class MonthViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    let collectionViewHeight: CGFloat = screenHeight - 24 - 64
    
    var collectionViewWidth: CGFloat! = nil
    var itemWidth: CGFloat! = nil
    var collectionViewLeading: CGFloat! = nil
    
    var historyY: CGFloat! = nil
    
    //硬适配！
    func prepareForCollectionView() {
        if screenWidth == 320.0 {
            collectionViewWidth = 318.0
            collectionViewLeading = 1.0
            itemWidth = 45.0
        } else if screenWidth == 375.0 {
            collectionViewWidth = 374.0
            collectionViewLeading = 0.5
            itemWidth = 53.0
        } else if screenWidth == 414.0 {
            collectionViewWidth = 415.0
            collectionViewLeading = -1.0
            itemWidth = 59.0
        } else {
            collectionViewLeading = 0.0
            collectionViewWidth = screenWidth
            itemWidth = (screenWidth-3)/7
        }
        
    }
    
    var date = NSDate()
    let cellId = "cell"
    var currentSection: NSInteger? {
        didSet {
            if currentSection == NSDate.month(date) - 1 && currentYear == NSDate.year(date) {
                self.backTodayButton?.hidden = true
            } else {
                self.backTodayButton?.hidden = false
            }
            updateEvents()
        }
    }
    
    let dayInMonthView = DayInMonthView()
    
    func updateEvents() {
        if currentSection == 0 {
            readAllEvents(currentSection!)
            readAllEvents(currentSection!+1)
        } else if currentSection == 11 {
            readAllEvents(currentSection!-1)
            readAllEvents(currentSection!)
        } else if (currentSection > 0) && (currentSection < 11){
            readAllEvents(currentSection!-1)
            readAllEvents(currentSection!)
            readAllEvents(currentSection!+1)
        }
    }
    
    func getEventMaxLineNum(section: Int) -> Int {
        
        return Int((collectionViewHeight / CGFloat(weekNumArray[section]) - 30) / MonthViewEventCellHeight)
    }

    func readAllEvents(currentSection: NSInteger) {
        
        let components = NSDateComponents()
        components.year = currentYear!
        components.month = currentSection + 1
        
        let calendar = NSCalendar.currentCalendar()
        let sectionDate = calendar.dateFromComponents(components)
        let firstWeekday = NSDate.firstDayInTheMonth(sectionDate!)
        
        let firstDay = firstDayOfMonthFromYear(currentSection)
        
        // 一月边界
        components.hour = 24
        components.minute = 0
        components.second = 0
        components.day = -firstWeekday
        let firstSectionDay = calendar.dateFromComponents(components)
        components.day = weekNumArray[currentSection]*7-firstWeekday+1
        let lastSectionDay = calendar.dateFromComponents(components)
        
        monthEventList = uiRealm.objects(Event).filter("timeBegin < %@ AND timeEnd > %@ AND calendarId = %@", lastSectionDay!, firstSectionDay!, NSUserDefaults.getCurrentCalendarId())
        components.day = -firstWeekday
        let maxLineNumber = self.getEventMaxLineNum(currentSection)
        for i in 0...(weekNumArray[currentSection]-1) {
            weekEventList = monthEventList.filter("timeBegin < %@ AND timeEnd > %@", NSDate.lastPlus1DayOfWeek(calendar.dateFromComponents(components)!), NSDate.firstDayOfWeek(calendar.dateFromComponents(components)!)).sorted("timeBegin")
            for j in 0...6 {
                var dayEvents = [EventInMonthView]()
                components.day = j + 7 * i - firstWeekday + 1
                components.minute = 0
                components.second = 0
                components.hour = 0
                let dayBegin = calendar.dateFromComponents(components)
                components.hour = 24
                let dayEnd = calendar.dateFromComponents(components)
                dayEvent = weekEventList.filter("timeBegin < %@ AND timeEnd > %@", dayEnd!, dayBegin!)
                for k in dayEvent {
                    dayInMonthView.insert(k.localId, isFinished: k.timeEnd <= dayEnd!)
                }
                for k in dayInMonthView.today {
                    let event = EventInMonthView()
                    if (k != 0) {
                        if let e = dayEvent.filter("localId == %i", k).first {
                            event.eventCircleType = e.getCircleIconType(dayBegin!, dateEnd: dayEnd!)
                            event.eventColorType = e.getColorType()
                            event.eventBarType = e.getBarType(dayBegin!, dateEnd: dayEnd!)
                            event.eventLineType = dayInMonthView.lineType(k)
                            event.eventLocalId = e.localId
                            if (e.isShowTitle(dayBegin!, dateEnd: dayEnd!)) {
                                event.eventTitle = e.summary
                            }
                        }
                    }
                    dayEvents.append(event)
                }
                eventNumList[firstDay + j + 7 * i] = dayInMonthView.getRemainNumber(maxLineNumber)
                dayInMonthView.move()
                totalEventList[firstDay + j + 7 * i] = dayEvents
            }
        }
    }
    
    var currentYear: NSInteger? {
        didSet {
            yearChanged()
        }
    }
    var weekNumArray = [NSInteger]()
    
    var dayEvent: Results<Event>!
    var weekEventList: Results<Event>!
    var monthEventList: Results<Event>!
    
    var totalEventList = Array<Array<EventInMonthView>>()
    var eventNumList = Array<Int>()
    
    func yearChanged() {
        var totalDays = 0
        weekNumArray.removeAll()
        for i in 1 ... 12 {
            let components = NSDateComponents()
            components.month = i
            components.year = currentYear!
            let date = NSCalendar.currentCalendar().dateFromComponents(components)!
            let weekNum = NSDate.totalWeeksInTheMonth(date)
            totalDays = totalDays + weekNum * 7
            weekNumArray.append(weekNum)
        }
        // 初始化一年的events
        totalEventList = Array<Array<EventInMonthView>>(count: totalDays, repeatedValue: [])
        eventNumList = Array<Int>(count: totalDays, repeatedValue: 0)
        self.collectionView.reloadData()
    }
    
    var collectionView: UICollectionView!
    var monthlabelView: UILabel!
    var weekOverTitleView: WeekOverTitleView!
    
    var notificationToken: NotificationToken?
    
    deinit {
        if let notificationToken = notificationToken {
            notificationToken.stop()
        }
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        self.prepareForCollectionView()
        
        weekOverTitleView = NSBundle.mainBundle().loadNibNamed("WeekOverTitleView", owner: self, options: nil).last as! WeekOverTitleView
        weekOverTitleView.frame = CGRectMake(0, 12, screenWidth, 24)
        weekOverTitleView.layer.shadowOffset = CGSizeMake(0, 3)
        weekOverTitleView.layer.shadowColor = UIColor.darkGrayColor().CGColor
        weekOverTitleView.layer.shadowRadius = 3
        weekOverTitleView.layer.shadowOpacity = 0.8
        weekOverTitleView.layer.cornerRadius = 2.5
        
        let layout = UICollectionViewFlowLayout()
        
        layout.sectionInset = UIEdgeInsetsMake(0.5, 0, 0, 0)
        layout.minimumLineSpacing = 0.5
        layout.minimumInteritemSpacing = 0
        
        collectionView = UICollectionView(frame: CGRectMake(collectionViewLeading, 24, collectionViewWidth, collectionViewHeight), collectionViewLayout: layout)
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsVerticalScrollIndicator = false
        self.collectionView.backgroundColor = YOKOColor.collectionViewBackgroundColor
        collectionView.bounces = false
        self.view.addSubview(collectionView)
        
        collectionView.registerNib(UINib(nibName: "OneDayItemCollectionCell", bundle: nil), forCellWithReuseIdentifier: cellId)
        
        currentYear = NSDate.year(date)
        currentSection = NSDate.month(date) - 1
        // 默认滚到当前月
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: true)
        
        self.updateNavigationTitle()
        
        self.initBackTodayButton()
        self.view.addSubview(weekOverTitleView)
        
        let realm = try! Realm()
        notificationToken = realm.addNotificationBlock { notification, realm in
            self.updateEvents()
            self.collectionView.reloadData()
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MonthViewController.changeCalendar(_:)), name: YOKONotification.CHANGE_CURRENT_CALENDAR, object: nil)
        
    }
    
    func changeCalendar(notification: NSNotification) {
        updateEvents()
        self.collectionView.reloadData()
    }
    
    // 回到今日按钮
    var backTodayButton: UIButton? = nil
    
    func firstDayOfMonthFromYear(currentSection: NSInteger)->NSInteger {
        var firstDayOfMonthFromYear = 0
        if (currentSection > 0) {
            for i in 0 ... (currentSection-1) {
                firstDayOfMonthFromYear = firstDayOfMonthFromYear + weekNumArray[i] * 7
            }
        }
        return firstDayOfMonthFromYear
    }
    
    func initBackTodayButton() {
        backTodayButton = UIButton.init(type: .Custom)
        backTodayButton?.setImage(UIImage(named: "今"), forState: .Normal)
        backTodayButton?.backgroundColor = UIColor.clearColor()
        backTodayButton!.frame = CGRectMake(screenWidth - 70, screenHeight - 124, 44, 44)
        
        backTodayButton!.layer.shadowOffset = CGSizeMake(0, 3)
        backTodayButton!.layer.shadowColor = UIColor.lightGrayColor().CGColor
        backTodayButton!.layer.shadowRadius = 3
        backTodayButton!.layer.shadowOpacity = 0.8
        backTodayButton!.layer.cornerRadius = 2.5
        
        self.view.addSubview(backTodayButton!)
        backTodayButton!.addTarget(self, action: #selector(self.backToday), forControlEvents: .TouchUpInside)
        
        backTodayButton?.hidden = true
    }
    
    func backToday() {
        let year = NSDate.year(date)
        let month = NSDate.month(date)
        
        self.selectMonth(year, month: month)
        
    }
    
    // 更新navi title
    func updateNavigationTitle() {
        let VC = self.parentViewController as! ViewController
        VC.setNavigationBarDate(String(format: "%i", currentYear!), month: String(format: "%i月", currentSection! + 1))
    }
    
    // 选择跳转月份
    func selectMonth(year: NSInteger, month: NSInteger) {
        self.currentYear = year
        self.currentSection = month - 1
        
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: true)
        
        self.updateNavigationTitle()
        updateEvents()
        self.collectionView.reloadData()
    }
    
    // MARK: - UICollectionViewDelegateFlowLayout
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        let lineNum = self.weekNumArray[indexPath.section]
        return CGSizeMake(itemWidth , collectionViewHeight / CGFloat(lineNum) - 0.5)
    }
    
    // MARK: - CollectionViewDelegate
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! OneDayItemCollectionCell
        
        let row = indexPath.row
        let section = indexPath.section
        
        let components = NSDateComponents()
        components.month = section + 1
        components.year = currentYear!
        
        let calendar = NSCalendar.currentCalendar()
        let sectionDate = calendar.dateFromComponents(components)
        let firstWeekday = NSDate.firstDayInTheMonth(sectionDate!) // 第一天是周几
        let dayNum = NSDate.totalDaysInTheMonth(sectionDate!) // 该月总共几天
        
        // 不是本月时间为灰色
        if row < firstWeekday || row > firstWeekday + dayNum - 1 {
            cell.dateLabel.textColor = UIColor.lightGrayColor()
            cell.labelBackgroundView.backgroundColor = YOKOColor.collectionViewItemGray
            cell.labelBackgroundView.alpha = 1
        } else {
            cell.dateLabel.textColor = YOKOColor.fontBlack
            cell.labelBackgroundView.backgroundColor = YOKOColor.TypeColors[0]
            cell.labelBackgroundView.alpha = 0.06
        }
        // 具体每个cell的时间
        components.day = row - firstWeekday + 1
        cell.date = calendar.dateFromComponents(components)
        
        let firstDay = firstDayOfMonthFromYear(section)
        cell.eventList = totalEventList[firstDay + row]
        
        cell.maxEventNum = getEventMaxLineNum(section)
        if eventNumList[firstDay + row] != 0 {
            if eventNumList[firstDay + row] > 9 {
                cell.maxNumLabel.text = String(format: "%i", eventNumList[firstDay + row])
            }else {
                cell.maxNumLabel.text = String(format: "+%i", eventNumList[firstDay + row])
            }
            cell.plusBackgroundView.hidden = false
        }else {
            cell.plusBackgroundView.hidden = true
            cell.maxNumLabel.text = ""
        }
        
        return cell
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 12
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.weekNumArray[section] * 7
    }
    
    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        let oneDayCell = cell as! OneDayItemCollectionCell
        
        oneDayCell.dateStringForCell()
        
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        historyY = scrollView.contentOffset.y
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        let offsetY = scrollView.contentOffset.y
        let height = scrollView.bounds.size.height
        
        let offset = offsetY / height
        if offset <= 0 {
            currentSection = 11
            // 滚到相应位置
            currentYear = currentYear! - 1
            // 改变年份
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: false)
            
        } else if offset >= 11 {
            currentSection = 0
            currentYear = currentYear! + 1
            // 改变年份
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: false)
        } else {
            currentSection = lrintf(Float(offset))
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: true)
            
        }
        
        if decelerate {
            var section: Int = 0
            if historyY-offsetY > 0 {
                section = currentSection! - 1
                
            } else if historyY-offsetY < 0 {
                section = currentSection! + 1
                
            }
            if section < -1 || section > 12 {
                return
            } else {
                currentSection = section
            }
            if currentSection == -1 {
                currentSection = 11
                // 滚到相应位置
                currentYear = currentYear! - 1
                // 改变年份
                self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: false)
            } else if currentSection == 12{
                currentSection = 0
                currentYear = currentYear! + 1
                // 改变年份
                self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: false)
            }
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forRow: 0, inSection: currentSection!), atScrollPosition: .Top, animated: true)
        }
        
        self.updateNavigationTitle()
        
    }
    
    var delegate: MonthViewControllerDelegate? = nil
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! OneDayItemCollectionCell
        // 计算View跳转展开的高度
        let row = Int(indexPath.row / 7)
        let height = 32 + 24 + (CGFloat(row) * cell.frame.height)
        
        self.delegate?.monthViewControllerToDayViewController(cell.date!, openUpHeight: height)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

